﻿using Pattern24解释器模式.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pattern24解释器模式.Models
{
    public sealed class Context
    {
        private Stack<Expression> stack = new Stack<Expression>();//栈
        private Expression direction, mode, distance, all;
        public void Execute(string content)
        {
            string[] array = content.Split(' ');

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] == "and")
                {
                    Expression left = stack.Pop();
                    direction = new DirectionExpression(array[++i]);
                    mode = new ModeExpression(array[++i]);
                    distance = new DistanceExpression(array[++i]);
                    Expression right = new TerminalExpression(direction, mode, distance);
                    Expression end = new NonTerminalExpression(left, right);
                    stack.Push(end);
                }
                else
                {
                    direction = new DirectionExpression(array[i]);
                    mode= new ModeExpression(array[++i]);
                    distance= new DistanceExpression(array[++i]);
                    Expression end = new TerminalExpression(direction, mode, distance);
                    stack.Push(end);
                }
            }

            all = stack.Pop();//弹出所有表达式
        }

        public string InterpretAll()
        {
            return all.Interpret();
        }
    }
}
